import React, { Component } from "react";
import PropTypes from "prop-types";
import Cropper from "react-cropper"; // 引入Cropper
import "cropperjs/dist/cropper.css"; // 引入Cropper对应的css
import { Modal, message } from 'antd';
import "./ClassCropperModal.scss";
import { getData, GUID } from "../js/fetch";
import $ from 'jquery';
// import base64
// import { ErrorAlert } from "../js/fetch/util";
const MAX_FILE_SIZE = 20 * 1024 * 1024; //文件最大限制为2MB
const BYTES_PER_SLICE = 3.9 * 1024 * 1024;
export default class ClassCropperModal extends Component {
  static propTypes = {
    // uploadedImageFile: PropTypes.object.isRequired,
    onClose: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    // onCheck: PropTypes.func.isRequired,
    Visiable: PropTypes.bool.isRequired,
    UpDataUrl: PropTypes.string.isRequired
  };

  constructor(props) {
    super(props);
    console.log(props, 'props.baseUrl');
    this.state = {
      src: null,
      classModalVisible: props.Visiable,
      classModalFile: null,
      title: props.title ? props.title : "上传图片",
      bodyStyle: props.bodyStyle ? props.bodyStyle : {},
      filename: props.filename ? props.filename : "",
      baseUrl: props.baseUrl ? props.baseUrl : "http://192.168.129.1:30101", //图片上传基地址
      aspectRatio: props.aspectRatio ? props.aspectRatio : 1
    };
  }

  componentWillMount() {
    const fileReader = new FileReader();
    fileReader.onload = e => {
      const dataURL = e.target.result;
      this.setState({ src: dataURL });
    };
    if (this.state.classModalFile !== null) {
      fileReader.readAsDataURL(this.state.classModalFile);
    }

    // console.log(this.props.Visiable)
  }

  handleSubmit = () => {
    if (this.state.classModalFile === null) {
      message.error('请先选择需要上传的图片~', 1.5);
      return false;
    }

    if (!this.state.submitting) {

      // let url = `/homepage_images` // 你要上传的url
      // 拿到文件名
      // let filename = this.props.uploadedImageFile.name
      if (!HTMLCanvasElement.prototype.toBlob) {
        Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
          value: function (callback, type, quality) {
            var canvas = this;
            setTimeout(function () {
              var binStr = atob(canvas.toDataURL(type, quality).split(',')[1]);
              var len = binStr.length;
              var arr = new Uint8Array(len);
              for (var i = 0; i < len; i++) {
                arr[i] = binStr.charCodeAt(i);
              }
              console.log(arr, 'arr');
              callback(new Blob([arr], { type: type || 'image/png' }));
            });
          }
        });
      }
      // TODO: 这里可以尝试修改上传图片的尺寸
      this.cropper.getCroppedCanvas().toBlob(blob => {
        // // 创造提交表单数据对象
        // const formData = new FormData();
        // 添加要上传的文件
        // formData.append(
        //   "files",
        //   blob,
        //   this.state.filename + "1." + blob.type.split("/")[1]
        // );
        // formData.append("files", blob);
        // formData.append("modelName", "images")
        // console.log(formData, 'formData', blob, '---', this.state.classModalFile)
        // console.log(blob.size);
        let fileType = blob.type;
        // console.log(fileType);
        this.setState({
          totalSize: blob.size,
          fileName: blob.name,
          hasSendNum: 0,
          totalSlices: Math.ceil(blob.size / BYTES_PER_SLICE),
        }, )
        let slice = blob.slice(0, BYTES_PER_SLICE);//切割文件

        let imgDataUrl = this.cropper.getCroppedCanvas().toDataURL('image/jpeg')
        let base64Img = imgDataUrl // base64编码的图片
        let imgFile = this.dataURLtoFile(base64Img)
           
        // console.log('imgFile====>', imgFile)
        // let str = this.dataURLtoFile(imgDataUrl)  
        // console.log('imgFile====>',this.getObjectURL(str));
        this.uploadFile(blob, slice, this.state.hasSendNum + 1, this.state.classModalFile, fileType, imgFile);
        // console.log(this.cropper.getCanvasData(),'data11111');

        // getData('publicinfo/GetServerInfo', {

        // },
        // ).then((res) => {
        //   return res.json();
        // }).then((json) => {
        //   if (json.code == 200) {
        //     this.uploadFile(blob, slice, this.state.hasSendNum + 1, this.state.classModalFile, fileType, json);
        //   }
        // })
        // 提示开始上传 (因为demo没有后端server, 所以这里代码我注释掉了, 这里是上传到服务器并拿到返回数据的代码)
        // this.setState({submitting: true})
        // 上传图片
        // const resp = await http.post(url, formData)
        // 拿到服务器返回的数据(resp)
        // console.log(resp)
        // 提示上传完毕
        // this.setState({submitting: false})
        // fetch(this.props.UpDataUrl, {
        //   method: "POST",
        //   // mode: "cors",
        //   // cache: "no-cache",
        //   // credentials: "omit",
        //   body: formData
        //   // redirect: "follow",
        //   // headers:{
        //   //     "Content-Type": "multipart/form-data"
        //   // }
        // })
        //   .then(response => {
        //     //当请求成功时直接返回response，失败则进行json解析返回失败信息
        //     if (response.status === 200) {
        //       return response;
        //     } else {
        //       return response.json().then(json => {
        //           // console.log(json)
        //         return Promise.reject(json);
        //       });
        //     }
        //   })

        //   .then(
        //     res => {
        //       let json = res.json()
        //       // console.log(json);

        //       if (json) return json;
        //       else return false;
        //     },
        //     err => {
        //       // console.log(err)
        //       message.error('服务器出现未知异常，请重试或联系管理员',2);

        //       return false;
        //     }
        //   )
        //   .then(json => {
        //     //   console.log(json)
        //     if (!json) {
        //       message.error('服务器出现未知异常，请重试或联系管理员',2);
        //       // let title = "服务器出现未知异常，请重试或联系管理员";
        //       // ReactDOM.render(
        //       //   eslint-disable-next-line react/react-in-jsx-scope
        //       //   <ErrorAlert
        //       //     //   key={"alert" + "400-" + Math.round(Math.random() * 10000)}
        //       //     show={true}
        //       //     title={title}
        //       //   />,
        //       //   document.getElementById("alert")
        //       // );
        //       return false;
        //     }
        //     if (json.result) {
        //       this.props.onSubmit(blob, json.filePath);
        //       this.props.onClose();
        //       this.setState({
        //         classModalFile: null
        //       });
        //     } else {
        //       console.log(json);
        //     }
        //   }).catch(e => {
        //     //获取错误信息并弹出
        //     console.log(e.message)
        //     // notification.error({
        //     //   message: e.message
        //     // });
        //   });



        //把选中裁切好的的图片传出去

        // 关闭弹窗
      });
    }
  };
  //转换base64图片
  dataURLtoFile(dataurl, filename = this.state.filename ? this.state.filename: 'file') {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let suffix = mime.split('/')[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], `${filename}.${suffix}`, {
      type: mime
    })
  }

  getObjectURL(file) {
    var url = null
    if (window.createObjectURL != undefined) {
      url = window.createObjectURL(file)
    } else if (window.URL != undefined) {
      url = window.URL.createObjectURL(file)
    } else if (window.webkitURL != undefined) {
      url = window.webkitURL.createObjectURL(file)
    }
    return url
  };

  uploadFile(blob, slice, index, file, fileType,  imgFile,guid) {


    console.log('blob：', blob, 'slice:', slice, index,  fileType, 'imgFile===>',imgFile ,);
    // console.log(file,'<====file');
    let $this = this;
    // console.log(slice.name,slice.size,slice.type.split("/")[1],'slice.name,slice.size,slice.type');
    if (!guid) {
      guid = new GUID().newGUID();
    }
    let formData = new FormData();
    // let formData = new FormData($('#' + formID)[0]);
    // let diskName = 'News/Attachment/' + json.data[0].ServerDate.slice(0, 4) + json.Data.ServerDate.slice(5, 7);
    // formData.append('method', 'doUpload_WholeFile');
    // formData.append('guid', guid);
    // formData.append('name', file.name);
    // formData.append('id', '');
    // formData.append('type', fileType);
    // formData.append('lastModifiedDate', file.lastModifiedDate);
    // formData.append('diskName', diskName);
    // formData.append('size', $this.state.totalSize);
    formData.append("modelName", "images");
    formData.append("files", imgFile);


    // let formData = new FormData();
    // let diskName = 'Que/Attachment/' + json.Data.ServerDate.slice(0, 4) + json.Data.ServerDate.slice(5, 7);
    // formData.append('userid', sessionStorage.getItem('UserID'));
    // formData.append('method', 'doUpload_Mobile');
    // formData.append('guid', guid);
    // formData.append('suffix', fileType);
    // // formData.append('id', '');
    // // formData.append('type', '');
    // formData.append('chunk', $this.state.hasSendNum);
    // formData.append('chunks', this.state.totalSlices);
    // formData.append('strFileBinary', slice);
    // // formData.append('lastModifiedDate', file.lastModifiedDate);
    // formData.append('diskName', diskName);
    // formData.append('size', file.size);
    // formData.append('file', slice);
    $.ajax({
      url:
        sessionStorage.getItem('itemUrl') + 
        'api/commons/file/batch/upload',
      type: 'POST',
      cache: false,
      data: formData,
      //dataType: 'json',
      //async: false,
      processData: false,
      contentType: false,
    })
      .done(function (res) {
        if(res.code == 200 ){
          // console.log('res',res);
          let imgUrl = res.data[0].url
          $this.props.onSubmit(imgUrl)
        }
        // console.log($this.state.hasSendNum, '$this.state.hasSendNum',$this.state.Visiable);
        $this.setState({
          hasSendNum: $this.state.hasSendNum,
          // Visiable: false
        }, () => {
          if (index == $this.state.totalSlices) {
            // let fileList = $this.state.fileList;
            // if (blob) {
            //     // console.log(diskName + '/' + guid + file.name.slice(file.name.lastIndexOf('.'), file.name.length));
            //     $this.setState({
            //         NewsTitleImg: diskName + '/' + guid + file.name.slice(file.name.lastIndexOf('.'), file.name.length),
            //     })
            // } else {
            //     $this.setState({
            //         isupload: false,
            //     })
            //     // message.success('上传成功~');
            //     $this.setState({
            //         AttachmentID: guid,
            //         AttachmentUrl: diskName + '/' + guid + file.name.slice(file.name.lastIndexOf('.'), file.name.length),
            //         AttachmentName: file.name,
            //         AttachmentSize: file.size,
            //         isupload: false,
            //     })

            // }
            // message.success('上传附件成功~');
            // $this.cancelSubmit(diskName + '/' + guid + file.name.slice(file.name.lastIndexOf('.'), file.name.length));
          } else {
            $this.setState({
              hasSendNum: $this.state.hasSendNum + 1
            }, () => {
              // console.log(index);

              // console.log(index*BYTES_PER_SLICE);
              let end = index * BYTES_PER_SLICE + BYTES_PER_SLICE;
              if (index * BYTES_PER_SLICE + BYTES_PER_SLICE >= blob.size) {
                end = blob.size
              }
              // console.log(blob);
              slice = blob.slice(index * BYTES_PER_SLICE, end);
              //  console.log(end);
              // console.log($this.state.hasSendNum);
              index = index + 1;
              $this.uploadFile(blob, slice, index, $this.state.classModalFile, fileType,imgFile)
            })
          }
        })
      }).fail(function () {
        if (blob) {
          $this.setState({
            NewsTitleImg: '',
          })
        } else {
          $this.setState({
            AttachmentID: '',
            AttachmentUrl: '',
            AttachmentName: '',
            AttachmentSize: '',
            isupload: false,
          })
          message.error('上传失败~');
        }

      });
  }

  cancelSubmit = (NewsTitleImg) => {
    this.props.onClose(NewsTitleImg);
    this.setState({
      classModalFile: null
    });
  };

  handleClassFileChange = e => {
    const file = e.target.files[0];
    if (file) {
      if (file.size <= MAX_FILE_SIZE) {
        if (file.type !== 'image/png' && file.type !== 'image/jpeg' && file.type !== 'image/jpg') {
          message.error('请上传JPG/JPEG/PNG格式的图片~', 1.5);
          return;
        }
        this.setState(
          {
            classModalFile: file // 先把上传的文件暂存在state中
          },
          () => {
            const fileReader = new FileReader();
            fileReader.onload = e => {
              const dataURL = e.target.result;
              this.setState({ src: dataURL });
            };

            fileReader.readAsDataURL(this.state.classModalFile);
          }
        );
      } else {
        message.error('图片大小不能超过20M~', 1.5);
        // ReactDOM.render(
        //   // eslint-disable-next-line react/react-in-jsx-scope
        //   // <ErrorAlert
        //   //   //   key={"alert" + "400-" + Math.round(Math.random() * 10000)}
        //   //   show={true}
        //   //   title={"文件过大"}
        //   // />,
        //   // document.getElementById("alert")
        // );

        //   this.props.onCheck("overSize")
        // console.log("文件过大");
      }
    }
    // console.log(this.state.classModalFile);
  };

  render() {
    const { classModalFile } = this.state;

    // console.log(this.props.Visiable,this.state.src);

    return (
      <Modal
        ref="handleAdminMadal"
        bodyStyle={{
          //   width: "724px",
          height: "473px",
          padding: 0,
          ...this.state.bodyStyle
        }}
        type="1"
        width="781px"
        centered
        destroyOnClose={true}
        title={this.state.title}
        visible={this.props.Visiable}
        footer={null}
        onOk={this.handleSubmit}
        onCancel={this.cancelSubmit}
      >
        {/* <div className="class-cropper-modal"> */}
        <div className="modal-panel">
          {/* <div className="modal-top">
                            <span className="modal-title">上传图片</span>'
                            <span className="modal-close" onClick={this.cancelSubmit}></span>
                        </div> */}
          <div className="upload-tips">
            <label className="btn choose-pic">
              <span className="inputBox">选择本地图片</span>
              <input
                type="file"
                style={{ display: "none" }}
                onChange={this.handleClassFileChange}
                accept="image/jpg,image/jpeg,image/png"
                className="btn choose-pic"
              />
            </label>
            上传要求：请上传JPG/JPEG/PNG格式的图片，图片大小不能超过20MB
          </div>
          {classModalFile === null ? <div className='updata-empty'><i></i><p>请上传本地图片</p></div> : <div className="cropper-container-container">
            <div
              className={`cropper-container ${classModalFile === null ? "default" : ""
                }`}
            >
              {classModalFile !== null ? (
                <div>
                  <Cropper
                    src={this.state.src}
                    className="cropper"
                    ref={cropper => (this.cropper = cropper)}
                    // Cropper.js options
                    viewMode={1}
                    zoomable={true}
                    aspectRatio={this.state.aspectRatio} // 固定为1:1  可以自己设置比例, 默认情况为自由比例
                    guides={true}
                    preview=".cropper-preview"
                    movable={true}
                    rotatable={false}
                    // zoomOnTouch={true}
                    // cropBoxMovable={true}
                    center={true}
                    highlight={true}
                    modal={false}
                    rotateTo={-90}
                  // scalable={true}
                  // toggleDragModeOnDblclick={true}
                  // moveTo={true}
                  // zoomOnWheel={true}
                  // responsive={true}
                  // background={false}
                  />
                  {/* <img src={this.state.src} alt='图片错误' /> */}
                  <p className="tips-p">提示: 请拖动窗口裁剪图片</p>
                </div>) : (
                ""
              )}
            </div>

            <div className="preview-container default">
              <p className="tips-p2">裁剪效果图</p>
              {/* <div className="cropper-preview " ></div>
              <div className="cropper-preview" ><div> */}
              {classModalFile !== null ? (
                <div className="cropper-preview"></div>
              ) : (
                ""
              )}
            </div>
          </div>}
          <div className="group-btn">
            <div className="cancel-btn" onClick={this.cancelSubmit}>取消</div>
            <div className="confirm-btn" onClick={this.handleSubmit}>确定</div>

          </div>
          {/* <div className="button-row">
                            <button className="submit-button" onClick={this.handleSubmit}>点击提交</button>
                            <button className="cancel-button" onClick={this.cancelSubmit}>取消</button>
                        </div> */}
        </div>
        {/* </div>{" "} */}
      </Modal>
    );
  }
}
